<script lang="ts" setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules, FormInstance } from 'element-plus'
import gdjdService from '@/api/gdjd'
import TreeUtil from '@/utils/tree'
import treeSelect from '@/components/tree-select-edl/index.vue'

const gdsxxJdList = ref<any>([])
const getGdsxxJd = (dwbm: string) => {
  gdjdService.queryJdbbxzlx({ dwbm }).then((res: any) => {
    gdsxxJdList.value = res.data
  })
}

const organizationList = ref<any[]>([])
const queryZzjg = () => {
  gdjdService.queryDownloadJdbbDws().then((res: any) => {
    organizationList.value = TreeUtil.getTreeData(res.data || [], 'dwbm', 'fdwbm')
  })
}
/*
 * 打开弹窗
 */
const dialogVisible = ref(false)
const multipleSelection = ref<any[]>([])
const openDialog = (rowData: any) => {
  queryZzjg()
  multipleSelection.value = rowData
  dialogVisible.value = true
}

// 保存借阅审核结果入参
const form = ref({
  dwbm: '',
  jdbbxzlxdm: '',
})

const rules = reactive<FormRules<any>>({
  jdbbxzlxdm: [{ required: true, message: '必填', trigger: 'change' }],
})

/*
 * 下载报表
 */
const ruleFormRef = ref()

const downloadJdbb = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const params = {
        dwbmList: [form.value.dwbm],
        jdbbxzlxdm: form.value.jdbbxzlxdm,
        jdbbbh: multipleSelection.value[0].jdbbbh,
      }
      gdjdService
        .downloadJdbb(params)
        .then((res: any) => {
          if (res.data.type === 'application/json') {
            const reader = new FileReader()
            reader.onload = () => {
              const jsonData =
                typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
              ElMessage({ type: 'warning', message: jsonData.message })
            }
            reader.readAsText(res.data)
          } else {
            const downloadElement = document.createElement('a')
            downloadElement.href = window.URL.createObjectURL(res.data)
            downloadElement.download = '监督报表.xlsx'
            document.body.appendChild(downloadElement)
            downloadElement.click() //点击下载
            document.body.removeChild(downloadElement) //下载完成移除元素
          }
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const closeDialog = () => {
  form.value = {
    dwbm: '',
    jdbbxzlxdm: '',
  }
  nextTick(() => {
    ruleFormRef.value?.resetFields()
  })
  dialogVisible.value = false
}
defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="报表下载"
    width="800px"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <div class="dialog-title">归档时效监督报表:</div>
    <div class="dialog-form">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="单位:">
          <tree-select
            ref="treeSelectRef"
            style="width: 100%"
            v-model="form.dwbm"
            node-key="dwbm"
            :treeProps="{
              children: 'children',
              label: 'dwmc',
              value: 'dwbm',
            }"
            :options="organizationList"
            :clearable="false"
            :check-strictly="false"
            :isLeafNode="false"
            @update:modelValue="getGdsxxJd"
          >
          </tree-select>
        </el-form-item>
        <el-form-item label="类型:" prop="jdbbxzlxdm">
          <el-select v-model="form.jdbbxzlxdm">
            <el-option
              v-for="item in gdsxxJdList"
              :key="item.xzlxdm"
              :label="item.xzlxmc"
              :value="item.xzlxdm"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" style="margin-left: 10px" @click="downloadJdbb(ruleFormRef)"
          >确定</el-button
        >
        <el-button type="default" style="margin-left: 10px" @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-title {
  padding: 15px 0;
}

.dialog-form {
  .el-form {
    display: flex;
    justify-content: center;
    align-items: center;
    .el-form-item {
      width: 50%;
    }

    .el-form-item:last-child {
      margin-left: 20px;
    }
  }
}
</style>
